package com.atyuntuku.yuntuku.aop;

import com.atyuntuku.yuntuku.annotation.AuthCheck;
import com.atyuntuku.yuntuku.common.ResultUtils;
import com.atyuntuku.yuntuku.common.UserRoleEnum;
import com.atyuntuku.yuntuku.exception.ErrorCode;
import com.atyuntuku.yuntuku.exception.ThrowUtils;
import com.atyuntuku.yuntuku.pojo.User;
import com.atyuntuku.yuntuku.utils.CommonUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * ClassName: Authinterceptor
 * Package: com.atyuntuku.yuntuku.aop
 * Description:
 *
 * @Author qinglong wei
 * @Create 2025/10/5 16:32
 * @Version 1.0
 */
@Aspect
@Component
public class Authinterceptor {

    /**
     * 给打上@AuthCheck注解的方法进行环绕增强
     */

    //这里面参数要小驼峰写法即使参数本身是大驼峰
   @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
       String mustAuth = authCheck.mustAuth();
       RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
       HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
     //获取当前登录用用户
       User currentUser = CommonUtils.getCurrentUser(request);
       ThrowUtils.throwIf(currentUser==null, ErrorCode.NO_AUTH_ERROR,"无权限，请先登录");

       //不需要权限就放行
       if(mustAuth == null)
       return joinPoint.proceed();

      UserRoleEnum mustrole = UserRoleEnum.getUserRole(mustAuth);
      ThrowUtils.throwIf(mustrole==null,ErrorCode.SYSTEM_ERROR,"系统错误，请联系管理员");
      if(!CommonUtils.isAdmin(currentUser)&&mustrole==UserRoleEnum.ADMIN)
      {
         return ResultUtils.error(ErrorCode.NO_AUTH_ERROR,"权限不足");
      }

      return joinPoint.proceed();
   }

}
